//
//  Product.m
//  Castlery
//
//  Created by xie weizhi on 8/8/17.
//  Copyright © 2017 xie weizhi. All rights reserved.
//

#import "Product.h"
#import "APIConfig.h"
#import <YYKit.h>

@implementation Product

///< Map model property to JSON key.
+ (NSDictionary *)modelCustomPropertyMapper {
    return @{@"productID" : @"id",
             @"title" : @"title",
             @"productDescription" : @"description",
             @"availableSince" : @"available_since",
             @"price" : @"price",
             @"imagePaths": @"images"
             };
}

- (BOOL)modelCustomTransformFromDictionary:(NSDictionary *)dic {
    NSString *dateString = dic[@"available_since"];
    if (dateString) {
        /// convert date string to local date string  2017-08-02 10:11:07 +0800
        
        NSDate *date = [NSDate dateWithString:dateString format:@"yyyy-MM-dd HH:mm:ssZ"];
        
        _availableSince = [date stringWithFormat:@"yyyy-MM-dd HH:mm:ss"
                                        timeZone:[NSTimeZone localTimeZone]
                                          locale:[NSLocale systemLocale]];
    }
    
    return YES;
}

#pragma mark - Public

- (NSURL *)firstImageURL {
    if (self.imagePaths.count == 0) {
        return nil;
    }
    
    return [NSURL URLWithString:[CastlerySeverIP stringByAppendingPathComponent:self.imagePaths.firstObject]];
}

- (NSArray <NSURL *> *)imageURLs {
    NSMutableArray *result = [NSMutableArray new];
    
    for (NSString *path in self.imagePaths) {
        NSURL *url = [NSURL URLWithString:[CastlerySeverIP stringByAppendingPathComponent:path]];
        [result addObject:url];
    }
    
    return result;
}

@end
